package com.mavenq.fly.utils;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Animal {
    void speak();
}

class Dog implements Animal {
    @Override
    public void speak() {
        System.out.println("Woof!");
    }
}

class AnimalFactory {
    public static Animal createAnimal(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return (Animal) ReflectionUtils.newInstance(clazz);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid animal class", e);
        }
    }


}

 class LoggingProxy implements InvocationHandler {
    private final Object target;

    public LoggingProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Method called: " + method.getName());
        return method.invoke(target, args);
    }

    // 创建代理对象
    public static <T> T createProxy(T target, Class<T> interfaceType) {
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class<?>[]{interfaceType}, new LoggingProxy(target));
    }
}


public class TestReflection {
    public static void main(String[] args) {
        // 直接调用
        Animal dog = AnimalFactory.createAnimal("com.mavenq.fly.utils.Dog");
        dog.speak();
        // 动态代理
        Animal animal = new Dog();
        Animal proxy = LoggingProxy.createProxy(animal, Animal.class);
        proxy.speak(); // 输出日志并调用实际方法
    }

}